package com.nifostasky.bloomfilter;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * 布隆过滤器简单实现
 * @author ludangxin
 * @date 2021/8/16
 */
@Slf4j
public class BloomFilterTest {
    /**
     * 预计要插入元素个数
     */
    private static final int SIZE = 1000000;
    /**
     * 误判率
     */
    private static final double FPP = 0.01;
    /**
     * 布隆过滤器
     */
    private static final BloomFilter<Integer> BLOOMFILTER = BloomFilter.create(Funnels.integerFunnel(), SIZE, FPP);

    @SneakyThrows
    public static void main(String[] args) {
        //插入数据
        for (int i = 0; i < 1000000; i++) {
            BLOOMFILTER.put(i);
        }
        int count = 0;
        // 过滤判断
        for (int i = 1000000; i < 3000000; i++) {
            if (BLOOMFILTER.mightContain(i)) {
                count++;
                log.info(i + new String("误判了".getBytes(StandardCharsets.UTF_8)));
            }
        }
        log.info(new String("总共的误判数".getBytes(StandardCharsets.UTF_8)) + count);
    }
}
